#!/usr/bin/env bash

# Copyright 2023 Flant JSC
# Licensed under the Deckhouse Platform Enterprise Edition (EE) license. See https://github.com/deckhouse/deckhouse/blob/main/ee/LICENSE

source /shell_lib.sh

function __config__(){
  cat <<EOF
configVersion: v1
kubernetes:
  - name: projects
    apiVersion: deckhouse.io/v1alpha1
    kind: Project
    queue: "projects"
    group: main
    executeHookOnEvent: []
    executeHookOnSynchronization: false
    keepFullObjectsInMemory: false
    jqFilter: |
      {
        "projectName": .metadata.name,
        "projectTypeName": .spec.projectTypeName
      }
kubernetesValidating:
- name: project-type.deckhouse.io
  group: main
  rules:
  - apiGroups:   ["deckhouse.io"]
    apiVersions: ["*"]
    operations:  ["CREATE", "DELETE"]
    resources:   ["projecttypes"]
    scope:       "Cluster"
EOF
}

function __main__() {
operation=$(context::jq -r '.review.request.operation')

if [ "$operation" == "DELETE" ]; then 
  projectTypeName=$(context::jq -r '.review.request.oldObject.metadata.name')

  if usedInProjectName="$(context::jq -er --arg typeName "$projectTypeName" '[.snapshots.projects[].filterResult | select(.projectTypeName == $typeName) | .projectName] | first' 2>&1)"; then
    cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":false, "message":"ProjectType \"$projectTypeName\" cannot be deleted. It is used in the Project \"$usedInProjectName\"" }
EOF
    return 0
  fi

    cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":true}
EOF
fi

if [ "$operation" == "CREATE" ]; then
  cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":false, "message":"ProjectType is deprecated, use the \"ProjectTemplate\" instead." }
EOF
  return 0
fi 

}

hook::run "$@"
